<template>
<div>
  <el-button type="primary" @click="handlClick">新增</el-button>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="商品名称">
      <el-input v-model="formInline.GoodName" placeholder="请输入商品名称" clearable />
    </el-form-item>
    <el-form-item label="生产批次">
      <el-input v-model="formInline.ProductionBatch" placeholder="请输入生产批次" clearable />
    </el-form-item>
    <el-form-item label="保质期（天）">
      <el-input v-model="formInline.ExprirationDate" placeholder="请输入保质期（天）" clearable />
    </el-form-item>
    <el-form-item label="生产许可证号">
      <el-input v-model="formInline.ProductionLicense" placeholder="请输入生产许可证号" clearable />
    </el-form-item>
    <el-form-item label="生产企业">
      <el-input v-model="formInline.ProductionEnterprise" placeholder="请输入生产企业" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getdata">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" />
    <el-table-column property="goodName" label="商品名称" />
    <el-table-column property="productionBatch" label="生产批次" />
    <el-table-column property="exprirationDate" label="保质期（天）" />
    <el-table-column property="productionLicense" label="生产许可证号" />
    <el-table-column property="productionEnterprise" label="生产企业" />
    <el-table-column property="address" label="信息完整度" />
    <el-table-column  label="操作" >
      <template #default="scoped">
        <el-button type="primary" size="small" @click="handleDomalia(scoped.row.traceabilityId)">详情</el-button>
        <el-button type="danger" size="small" @click="handleUpdate">修改</el-button>
        <el-button type="danger" size="small" @click="handleExport(scoped.row.traceabilityId)">导出溯源码</el-button>
        <el-button type="danger" size="small" @click="handleDelete">删除</el-button>
      </template>
    </el-table-column>
  </el-table>



  <el-dialog
    v-model="dialogVisible"
    title="Tips"
    width="500"
    :before-close="handleClose"
  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="商品名称" prop="goodId">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
   <el-form-item label="生产批次" prop="productionBatch">
      <el-input v-model="ruleForm.productionBatch" />
    </el-form-item>
    <el-form-item label="保质期（天）" prop="exprirationDate">
      <el-input v-model="ruleForm.exprirationDate" />
    </el-form-item>
    <el-form-item label="生产许可证号" prop="productionLicense">
      <el-input v-model="ruleForm.productionLicense" />
    </el-form-item>
    <el-form-item label="生产企业" prop="productionEnterprise">
      <el-input v-model="ruleForm.productionEnterprise" />
    </el-form-item>
    <el-form-item label="封面图" prop="goverImarger">
      <el-upload
    class="avatar-uploader"
    action="http://localhost:5020/api/Uploadss/Upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="ruleForm.goverImarger" :src="ruleForm.goverImarger" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </el-form-item>
  </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>




   
</template>

<script lang="ts" setup>
import { ElTable } from 'element-plus'
import axios from 'axios'
import { ref,onMounted ,reactive} from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { UploadFile } from 'element-plus'
import { UploadRawFile } from 'element-plus'
import { UploadUserFile } from 'element-plus'
import {useRouter} from 'vue-router'
import Cookies from 'cookies-ts'
import type { UploadProps } from 'element-plus'
const router=useRouter()
const cookie = new Cookies();
//生命周期函数钩
onMounted(()=>{
    getdata()
})
//条件
const formInline=ref({
  GoodName:"",
  ProductionBatch:"",
  ExprirationDate:0,
  ProductionLicense:"",
  ProductionEnterprise:""
})
//分页对象
const page=ref({
  PageIndex:1,
  PageSize:3,
  PageCount:0,
  RecourdCount:0
})
//弹框属性
const dialogVisible = ref(false)
//显示
const tableData=ref([])
 const getdata=()=>{
   axios.get("http://localhost:5058/api/TraceabilityManagements/GetShow",{
     params:{
       GoodName:formInline.value.GoodName,
       ProductionBatch:formInline.value.ProductionBatch,
       ExprirationDate:formInline.value.ExprirationDate,
       ProductionLicense:formInline.value.ProductionLicense,
       ProductionEnterprise:formInline.value.ProductionEnterprise,
       PageIndex:page.value.PageIndex,
       PageSize:page.value.PageSize
     }
   }).then(res=>{
     tableData.value=res.data.data.data
     page.value.PageCount=res.data.data.pageCount
     page.value.RecourdCount=res.data.data.recourdCount
   })
 }
//是否显示弹框
 const handlClick=()=>{
   dialogVisible.value=true
 }






//添加字段接口
 interface RuleForm {
  goodId: string
  productionBatch: string
  exprirationDate: string
  productionLicense: string
  productionEnterprise: string
  goverImarger: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  goodId: '',
  productionBatch: '',
  exprirationDate: '',
  productionLicense: '',
  productionEnterprise: '',
  goverImarger: "",
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  productionBatch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
  ],
  goodId: [
    {
      required: true,
      message: '请选择商品',
      trigger: 'change',
    },
  ],
  exprirationDate: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
  ],
   productionLicense: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
  ],
 productionEnterprise: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("").then(res=>{
        if(res.data.isSuc){
          ElMessage.success('添加成功')
          dialogVisible.value = false
          formEl.resetFields()
          getdata()
        }
        else{
          ElMessage.error('添加失败')
          dialogVisible.value = false
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  dialogVisible.value = false
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))



const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.goverImarger ="http://localhost:5020/"+ response
  console.log(ruleForm.goverImarger);
  console.log(response);
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/png', 'image/jpeg'].includes(rawFile.type)) {
    ElMessage.error('请上传png/jpg格式的图片!')
    return false
} else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

//导出
const handleExport=(id:number)=>{

}

const Exporttext=()=>{
  axios.post("").then(res=>{
    console.log(res.data);
  })
}


//删除
const handleDelete=(id:number)=>{
  ElMessageBox.confirm(
    '确定删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.delete("http://localhost:5020/api/InsertTraceabilityManagements/DelTraceability?TraceabilityId="+id).then(res=>{
    if(res.data.isSuc){
      ElMessage.success('删除成功')
      getdata()
    }else{
      ElMessage.error('删除失败')
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
 
}



//跳转详情
const handleDomalia = (pTime: number) => {
  cookie.set('pTimeId', pTime);
    // alert(1);
    // alert(pTime);
   router.push({
    path: '/BreedingEnterpriseForOneView',
    query: {
      TraceabilityId: pTime,
    },
  })

}
</script>



<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}goverImarger.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}




</style>

